<?php
namespace Cli\Controller;
class TagsController extends CommonController {
    public function updateSiteTags() {
        $start_time = NOW_TIME;
        $end_time = $start_time - 86400;

        $offset = 0;
        $limit = 10000;
        $Article = D('Article','Mysql');
        $Tags = D('Tags','Mysql');
        $SiteTags = D('SiteTags','Mysql');

        $where = "`updatetime` BETWEEN '{$start_time},{$end_time}' and `tags` is not null and `tags` <> ''";
        while(true) {
            
            $list = $Article->where($where)->field('mongoid,sid,tags')->limit($offset.','.$limit)->select();

            if(!$list) break;

            $tagList = array();
            $siteTags = array();
            foreach($list as $value) {
                $info = explode(',',$value['tags']);

                if(!$info) continue;

                foreach($info as $tagname) {
                    $tagList[$tagname] = 0;
                    $siteTags[$value['sid']][$tagname] = array();
                }
            }

            foreach($tagList as $tagname=>$value) {
                $info = $Tags->getByTitle($tagname);
                if(!$info) {
                    $tagid = $Tags->addTag($tagname);
                }else {
                    $tagid = $info['id'];
                }
                $tagList[$tagname] = $tagid;
            }

            foreach($siteTags as $sid=>$tags) {
                foreach($tags as $tagname=>$info) {
                    if(!isset($tagList[$tagname])) continue;
                    $count = $Article->where("`tags` like '%{$tagname}%' and `status` = 1")->count();

                    $tagInfo = $SiteTags->where("`sid`={$sid} and `tagid` = {$tagList[$tagname]}")->find();
                    if($tagInfo) {
                        $siteTagId = $tagInfo['id'];

                        $result = $SiteTags->save(array(
                            'id'        =>  $siteTagId,
                            'num'       =>  $count,
                            'updatetime'=>  NOW_TIME,
                        ));
                    }else {
                        $siteTagId = $SiteTags->add(array(
                            'sid'   =>  $sid,
                            'tagid' =>  $tagList[$tagname],
                            'num'   =>  $count,
                            'createtime'    =>  NOW_TIME,
                            'updatetime'    =>  NOW_TIME,
                        ));
                    }
                }
            }

            $offset += $limit;
        }
    }
}
?>
